<template>
	<view class="update">
		<view class="update-logo">
			<image src="/static/logo.png" mode="aspectFit"></image>
		</view>
		<view class="update-prog-wrap">
			<text class="update-title">{{text}}</text>
			<view class="update-prog">
				<progress
					:percent="upgrade"
					activeColor="#6eb92b"
					active
					stroke-width="8"
					class="progress"
				/>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapActions, mapGetters } from 'vuex';
	export default {
		data() {
			return {
				platform: uni.getSystemInfoSync().platform,
				text: '正在检查更新，请稍等',
				upgrade: 0,
				sVersion: '',
				update: ''
			};
		},
		onShow () {
			// #ifdef APP-PLUS
				this.update = this.updateInfo
				this.checkUpdates(this.updateInfo)
			// #endif
		},
		computed: {
			...mapGetters({
				updateInfo: 'getUpdate'
			})
		},
		methods: {
			...mapActions(['logOut']),
			checkUpdates (info) {
				/*
				 * 检查更新
				 * 1、检查本地缓存版本号
				 * sVersion storage 本地缓存版本
				 * mVersion manifest.json 版本
				*/
				const sVersion = plus.storage.getItem('sVersion');

				if (!sVersion) {
					this.getWidgetInfo().then(data => {
						this.sVersion = data;
						this.detectUpgrade(info); // 发起更新
					});
					return
				}
				this.sVersion = sVersion;
				this.detectUpgrade(info);
			},
			checkVersion (mVersion) {
				const oldV = Number(mVersion.replace(/\./g, ""));
				const newV = Number(this.sVersion.replace(/\./g, ""));
				return oldV > newV ? true : false
			},
			detectUpgrade (info) {
				/*
				 * 更新类型
				 * 0: 热更新
				 * 1: 安装包下载
				*/
				let checkVersion = this.checkVersion(info.version)
				if (!checkVersion) {
					this.text = '当前版本为最新版本' + this.sVersion
					this.upgrade = 0
					return
				}
				//需要升级
				let updateUrl = ""
				let downloadUrl = ""
				if (this.platform == "android") {
				  updateUrl = info["android"].update
				  downloadUrl = info["android"].download
				} else {
				  updateUrl = info["ios"].update
				  downloadUrl = info["ios"].download
				}
				switch(this.update.type){
					case "0":
						this.AppUpdate(updateUrl)
						return
					case "1":
						this.AppDownload(downloadUrl)
						return
					default:
				}
				
			},
			AppDownload (url) {
				this.logOut()
				try {
					uni.setStorageSync('bht_userInfo', {});
				} catch (e) {
					// error
				}
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/user/login/index'
					});
				}, 1000);
				plus.runtime.openURL(url);
			},
			AppUpdate (url) {
				this.text = '正在下载更新文件...'
				const downloadTask = uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							this.text = '下载成功，正在安装...'
							plus.io.resolveLocalFileSystemURL(res.tempFilePath, entry => {
								entry.file(fs => {
									this.installWgt(res.tempFilePath).then(e => {
										 plus.storage.setItem(
										 	'sVersion',
										 	this.sVersion
										 );
										entry.remove()
									})
								})
							})
							return
						}
						this.text = '下载失败，请检查网络'
						uni.showToast({
							title: '下载失败，请检查网络',
							icon: 'none'
						});
					},
					fail: () => {
						this.text = '下载失败，请检查网络'
						uni.showToast({
							title: '下载失败，请检查网络',
							icon: 'none'
						});
					}
				});
				downloadTask.onProgressUpdate((res) => {
					this.upgrade = parseInt(res.progress)
				});
			},
			installWgt (path) {
				return new Promise(resolve => {
					plus.runtime.install(path, {}, () => {
						this.text = '更新成功';
						uni.showModal({
							title: '提示',
							content: '更新完成',
							showCancel: false,
							success: res => {
								plus.runtime.restart() // 重启应用
							}
						})
						resolve()
					}, e => {
						this.text = '安装失败'; 
						this.upgrade = 0
						plus.nativeUI.alert("安装失败["+e.code+"]："+e.message); 
						resolve()
					})
				})
			},
			getWidgetInfo() {
				return new Promise(resolve => {
					plus.runtime.getProperty(plus.runtime.appid, wgtinfo => {
						resolve(wgtinfo.version);
					});
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.update {
		&-logo {
			width: 160upx;
			height: 160upx;
			margin: 250upx auto 60upx auto;
			text-align: center;
			margin: 50upx auto 60upx auto;
		}
		&-prog-wrap{
			padding: 50upx 40upx;
		}
		&-title {
			display: block;
			width: 100%;
			margin-bottom: 30upx;
			text-align: center;
		}
	}
</style>
